//
//  QSUMengManager.swift
//  TestSwift
//
//  Created by Song on 2018/7/4.
//  Copyright © 2018年 Song. All rights reserved.
//

/// 集成步骤：
/// 1、导入SDK
/// 2、添加白名单
/// 3、设置Schemes
/// 4、在桥接文件中导入：#import <UMSocialCore/UMSocialCore.h>

import UIKit

/// 配置平台需要的数据
struct QSPlatformInfo {
    var platformType: UMSocialPlatformType
    var appKey: String
    var appSecret: String? = nil
    var redirectURL: String? = nil
}

class QSUMengManager: NSObject {
    /// 注册友盟
    class func qs_registerUMeng(platformArray: Array<QSPlatformInfo>) {
        // 是否打开日志
        #if DEBUG
        UMSocialManager.default().openLog(true)
        #else
        UMSocialManager.default().openLog(false)
        #endif
        UMSocialGlobal.shareInstance().isClearCacheWhenGetUserInfo = true
        
        // 设置友盟appkey
        UMConfigure.initWithAppkey(kUMengAppKey, channel: "App Store")
        
        //配置微信平台的Universal Links
        //微信和QQ完整版会校验合法的universalLink，不设置会在初始化平台失败
        UMSocialGlobal.shareInstance()?.universalLinkDic = [UMSocialPlatformType.wechatSession.rawValue: "https://baidu.com"]
        
        // 配置平台
        self.configPlatforms(platformArray: platformArray)
    }
    
    /// 配置平台
    private class func configPlatforms(platformArray: Array<QSPlatformInfo>) {
        for platformInfo in platformArray {
            UMSocialManager.default().setPlaform(platformInfo.platformType, appKey: platformInfo.appKey, appSecret: platformInfo.appSecret, redirectURL: platformInfo.redirectURL)
        }
    }
    
    /// 授权登录
    ///
    /// - Parameters:
    ///   - platformType: 平台
    ///   - success: 授权成功回调
    class func qs_login(platformType: UMSocialPlatformType, success:@escaping ((UMSocialUserInfoResponse) -> (Void))) {
        UMSocialManager.default().getUserInfo(with: platformType, currentViewController: nil) { (result, error) in
            if error == nil {
                let resp: UMSocialUserInfoResponse = result as! UMSocialUserInfoResponse
                
                success(resp)
            } else {
                #if DEBUG
                print("授权失败！")
                #endif
            }
        }
    }
    
    /// 分享链接
    ///
    /// - Parameters:
    ///   - platformType: 平台
    ///   - title: 分享title
    ///   - desc: 分享描述
    ///   - thumbImg: 分享缩略图
    ///   - webPageUrl: 分享网页地址
    class func qs_shareWebPage(platformType: UMSocialPlatformType, title: String?, desc: String?, thumbImg: Any?, webPageUrl: String?) {
        // 处理缩略图
        let tempThumbImg = self.dealWithThumbImage(thumbImg)
        
        //创建网页内容对象
        let shareObject = UMShareWebpageObject.shareObject(withTitle: title, descr: desc, thumImage: tempThumbImg)
        //设置网页地址
        shareObject?.webpageUrl = webPageUrl
        
        //创建分享消息对象
        let messageObject = UMSocialMessageObject.init()
        messageObject.shareObject = shareObject
        
        // 调用分享接口
        UMSocialManager.default().share(to: platformType, messageObject: messageObject, currentViewController: nil) { (data, error) in
            if error == nil {
                QSHud.qs_showSuccess(title: "分享成功！")
            }
        }
    }
    
    /// 分享图片
    ///
    /// - Parameters:
    ///   - platformType: 平台
    ///   - thumbImg: 分享缩略图
    ///   - shareImg: 分享图片
    class func qs_shareImage(platformType: UMSocialPlatformType, thumbImg: Any?, shareImg: Any?) {
        //创建分享消息对象
        let messageObject = UMSocialMessageObject.init()
        
        //创建图片内容对象
        let shareObject = UMShareImageObject.init()
        
        //如果有缩略图，则设置缩略图
        if thumbImg != nil {
            let tempThumbImg = self.dealWithThumbImage(thumbImg)
            
            shareObject.thumbImage = tempThumbImg
        }
        
        shareObject.shareImage = shareImg
        
        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject
        
        //调用分享接口
        UMSocialManager.default().share(to: platformType, messageObject: messageObject, currentViewController: nil) { (data, error) in
            if error == nil {
                QSHud.qs_showSuccess(title: "分享成功！")
            }
        }
    }
    
    /// 系统自带的分享
    ///
    /// - Parameters:
    ///   - title: 分享title
    ///   - thumbImg: 分享缩略图
    ///   - webPageUrl: 分享网页地址
    class func qs_showSystemShareView(title: String?, thumbImg: Any?, webPageUrl: String?) {
        // 分享的标题
        let textToShare = title
        
        // 分享的图片
        let imageToShare = self.dealWithThumbImage(thumbImg)
        
        // 分享的url
        let urlToShare = URL.init(string: webPageUrl!)
        
        //在这里呢 如果想分享图片 就把图片添加进去  文字什么的通上
        let activityItems = [textToShare ?? "", imageToShare, urlToShare ?? ""] as [Any]
        let activityVC = UIActivityViewController.init(activityItems: activityItems, applicationActivities: nil)
        
        //不出现在活动项目
        activityVC.excludedActivityTypes = [UIActivityType.print, UIActivityType.copyToPasteboard, UIActivityType.assignToContact, UIActivityType.saveToCameraRoll]
        if let currentVC = self.getCurrentViewController() {
            currentVC.present(activityVC, animated: true, completion: nil)
        }
        
        activityVC.completionWithItemsHandler = { (activityType, completed, returnedItems, activityError) in
            if (completed) {
                QSHud.qs_showSuccess(title: "分享成功！")
            } else  {
                //分享 取消
                QSHud.qs_showText(title: "用户取消分享！")
            }
        }
    }
    
    // MARK: - Private Methods
    /// 压缩图片
    ///
    /// - Parameters:
    ///   - image: 要压缩的图片
    ///   - maxFileSize: 压缩后的尺寸
    /// - Returns: 压缩后的图片
    private class func compressImage(image: UIImage, maxFileSize: Int) -> UIImage {
        var compression: CGFloat = 0.9
        let maxCompression: CGFloat = 0.1
        
        var imageData: Data = UIImageJPEGRepresentation(image, compression)!
        
        while imageData.count > maxFileSize && compression > maxCompression {
            compression -= 0.1
            
            imageData = UIImageJPEGRepresentation(image, compression)!
        }
        
        let compressedImage = UIImage.init(data: imageData)
        
        return compressedImage!
    }
    
    /// 处理缩略图
    ///
    /// - Parameter image: 缩略图
    /// - Returns: 处理后的缩略图
    private class func dealWithThumbImage(_ image: Any?) -> Any {
        var tempThumbImg = image
        
        // 对缩略图的处理
        var data = Data.init()
        if tempThumbImg is UIImage {
            data = UIImageJPEGRepresentation(image as! UIImage, 1.0)!
        } else if tempThumbImg is String {
            do {
                var imgUrlStr = tempThumbImg as! String
                
                if !(imgUrlStr.hasPrefix("http://") || imgUrlStr.hasPrefix("https://")) {
                    if (imgUrlStr.hasPrefix("/")) {
                        let startIndex = imgUrlStr.startIndex
                        imgUrlStr.remove(at: startIndex)
                    }
                    imgUrlStr = "\(HOST)\(imgUrlStr)"
                    tempThumbImg = imgUrlStr
                }
                
                // url编码
                let encodedValue = (tempThumbImg as! String).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
                data = try Data.init(contentsOf: URL.init(string: encodedValue!)!)
            } catch {
            }
            tempThumbImg = data
        } else if tempThumbImg is Data {
            data = tempThumbImg as! Data
        }
        
        if data.count > 32000 {
            let img = UIImage.init(data: data)
            let compressImage = self.compressImage(image: img!, maxFileSize: 32000)
            
            tempThumbImg = compressImage
        }
        
        if data.count < 1 {
            tempThumbImg = UIImage.init(named: kDefaultThumbImg)!
        }
        
        if tempThumbImg is Data {
            tempThumbImg = UIImage.init(data: tempThumbImg as! Data)
        }
        
        return tempThumbImg ?? UIImage.init(named: kDefaultThumbImg)!
    }
    
    /// 获取当前控制器
    private class func getCurrentViewController() -> UIViewController? {
        if let rootViewController = UIApplication.shared.keyWindow?.rootViewController{
            
            if (rootViewController.isKind(of: UITabBarController.self)) {
                let tabBarController = rootViewController as! UITabBarController
                return tabBarController.selectedViewController!
            }
            
            if (rootViewController.isKind(of: UINavigationController.self)) {
                let navigationController = rootViewController as! UINavigationController
                return navigationController.visibleViewController!
            }
            
            if ((rootViewController.presentedViewController) != nil) {
                return rootViewController.presentedViewController!
            }
            
            return rootViewController
        }else{
            return nil
        }
    }
}
